﻿// ***********************************************************************
// Assembly         : SecurityLayer
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="LogOnController.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using EmitMapper;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using InnovaApp.Layers.SecurityLayer.Models.AccountModels.MembershipServices;
using InnovaApp.Layers.SecurityLayer.Models.MetaModels;
using InnovaApp.Layers.SecurityLayer.Models.ViewModels._LayoutViewModels;
using INNOVACALL.Framework.Common;

namespace InnovaApp.Layers.SecurityLayer.Controllers.ViewControllers.LayoutViewControllers
{
    /// <summary>
    /// Class LogOnController
    /// </summary>
    public class LogOnController : _LayoutViewControllers_Base<LogOn_ViewModel>
    {
        /// <summary>
        /// Gets or sets the forms service.
        /// </summary>
        /// <value>The forms service.</value>
        public IFormsAuthenticationService FormsService { get; set; }
        /// <summary>
        /// Gets or sets the membership service.
        /// </summary>
        /// <value>The membership service.</value>
        public IMembershipService MembershipService { get; set; }

        /// <summary>
        /// Initialise des données qui peuvent ne pas être disponibles lorsque le constructeur est appelé.
        /// </summary>
        /// <param name="requestContext">Contexte HTTP et données d'itinéraire.</param>
        protected override void Initialize(RequestContext requestContext)
        {
            base.eMethodBase = "InnovaApp.Layers.SecurityLayer.Controllers.LogOnController";
            base.specificCssCollection = new string[] { "Views/Account/AccountCommon.css", "ClientComponents/KendoUI/kendo." + InnovaApp.Layers.CommonLayer.Controllers.Environment.KendoUITheme + ".min.css" };
            base.specificJSCollection = null;
            base.dynamicJSCollection = new string[] { "/ScriptsG/LogOnDynamic.js" };
            base.specificJqueryJSCollection = new string[] { "Views/LogOn.js" };
            base.externalCss = null;
            base.jsVariables = null;
            base.Meta.Add(enMeta.Description, Resources.View_LogOn_Meta_Description);
            base.Meta.Add(enMeta.Keywords, Resources.View_LogOn_Meta_Keywords);
            base.Meta.Add(enMeta.Subject, Resources.View_LogOn_Meta_Subject);

            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            base.Initialize(requestContext);
        }

        #region LogOn

        /// <summary>
        /// Selects the language.
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult SelectLanguage()
        {
            return Redirect(string.Format("/{0}{1}", base.URLReferLanguage, Request.Url.PathAndQuery));
        }

        /// <summary>
        /// URL: /en-us/LogOn
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult Index()
        {
            string eMethod = eMethodBase + ".Index[GET]";
            string language = base.URLReferLanguage;
            base.LocalizeDynamicScript(language);

            using (DataRepositories _dataContext = new DataRepositories())
            {
                base.InitView_Common(
                    pageTitle: Resources.View_LogOn_PageTitle,
                    openingMessage: string.Empty,
                    specificCssCollection: specificCssCollection,
                    specificJSCollection: specificJSCollection,
                    dynamicJSCollection: dynamicJSCollection,
                    specificJqueryJSCollection: specificJqueryJSCollection,
                    jsVariables: jsVariables,
                    externalJs: externalJs,
                    externalCss: externalCss,
                    metaToAdd: Meta,
                    _dataContext: _dataContext,
                    displayMenus: false,
                    language: base.RequestLanguage,
                    adminMode: false,
                    usesKendoUI: true,
                    jQueryUITheme: null,
                    kendoUITheme: null,
                    currentUser: Membership.GetUser()
                    );
            }
            string returnUrl = Request.QueryString["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                ContentData.ReturnUrl = returnUrl;
            }
            return View(ContentData);
        }

        //ToDo transformer le logon en ajax
        /// <summary>
        /// Indexes the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns>ActionResult.</returns>
        [HttpPost]
        public ActionResult Index(LogOn_ViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (DataRepositories _dataContext = new DataRepositories())
                {
                    if (MembershipService.ValidateUser(model.Credentials.UserName, model.Credentials.Password))
                    {
                        FormsService.SignIn(model.Credentials.UserName, model.Credentials.RememberMe);

                        if (Url.IsLocalUrl(model.ReturnUrl))
                        {
                            return Redirect(model.ReturnUrl);
                        }
                        else
                        {
                            return RedirectPermanent("/");
                        }
                    }
                    else
                    {
                        string eMethod = eMethodBase + ".Index[Post]";
                        string language = base.URLReferLanguage;
                        base.LocalizeDynamicScript(language);
                        
                        //In this case, we return to the same page, we need to re initialize view.
                        base.InitView_Common(
                            pageTitle: Resources.View_LogOn_PageTitle,
                            openingMessage: Resources.View_LogOn_AuthenticationFailed_Message,
                            specificCssCollection: specificCssCollection,
                            specificJSCollection: specificJSCollection,
                            dynamicJSCollection: dynamicJSCollection,
                            specificJqueryJSCollection: specificJqueryJSCollection,
                            jsVariables: jsVariables,
                            externalJs: externalJs,
                            externalCss: externalCss,
                            metaToAdd: Meta,
                            _dataContext: _dataContext,
                            displayMenus: false,
                            language: base.RequestLanguage,
                            adminMode: false,
                            usesKendoUI: true,
                            jQueryUITheme: null,
                            kendoUITheme: null,
                            currentUser: Membership.GetUser()
                            );
                        if (string.IsNullOrEmpty(model.Credentials.Language))
                        {
                            model.Credentials.Language = base.RequestLanguage;
                        }
                        ContentData.Credentials = ObjectMapperManager.DefaultInstance.GetMapper<LogOn_MetaModel, LogOn_MetaModel>().Map(model.Credentials);
                    }
                }
            }
            return View(ContentData);
        }

        #endregion

        #region LogOff

        /// <summary>
        /// URL: /Account/LogOff
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult LogOff()
        {
            FormsService.SignOut();
            Session.Abandon();
            return RedirectPermanent("~/");
        }

        #endregion
    }
}
